//
//  ListOrderViewController.swift
//  AutoPrint
//
//  Created by David on 16/10/11.
//  Copyright © 2016年 fatcat. All rights reserved.
//  订单显示页面

import UIKit
import MapKit

class ListOrderViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, GetScanViewControllerDelegate, PayViewControllerDelegate {

    
    var tableView: UITableView!
    
    var orderItems: NSArray!
    
    var loginPleaseBtn: UIButton! // 请先登录 按钮
    var logined = false // 是否登录
    var spinnerBG:UIView! // 加载菊花
    var refreshControl: UDRefreshControl!
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        title = "我的订单"
        
        tableView = UITableView(frame: view.frame, style: .grouped)
        view.addSubview(tableView)
        
        orderItems = NSArray()
        
        
        // 未登录时显示的请登录按钮，缺图标
        loginPleaseBtn = UIButton(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
        loginPleaseBtn.center = CGPoint(x: view.center.x, y: view.center.y - 64)
        loginPleaseBtn.backgroundColor = UIColor.lightGray
        loginPleaseBtn.setTitle("请先登录", for: UIControlState())
        loginPleaseBtn.setTitleColor(UIColor.white, for: UIControlState())
        loginPleaseBtn.layer.cornerRadius = 50
        loginPleaseBtn.addTarget(self, action: #selector(ListOrderViewController.gotoLogin), for: .touchUpInside)
        loginPleaseBtn.alpha = 0
        tableView.addSubview(loginPleaseBtn)
        
        // 加载菊花
        spinnerBG = UIView(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
        spinnerBG.center = view.center
        spinnerBG.backgroundColor = UIColor(white: 0, alpha: 0.75)
        spinnerBG.layer.cornerRadius = 5
        view.addSubview(spinnerBG)
        let spinner = UIActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
        spinner.center = CGPoint(x: 25, y: 25)
        spinner.activityIndicatorViewStyle = .white
        spinner.startAnimating()
        spinnerBG.addSubview(spinner)
        spinnerBG.alpha = 0
        
        // 下拉刷新提示器
        refreshControl = UDRefreshControl(frame: CGRect(x: 0, y: -64, width: view.bounds.width, height: 64))
        tableView.addSubview(refreshControl)
        
        // 是否登录，登陆后才能看
        if UserDefaults.standard.object(forKey: "user") != nil && UserDefaults.standard.object(forKey: "cookies") != nil {
            logined = true
            if FileManager.default.fileExists(atPath: "\(CACHES_PATH)/OrderList.plist"){
                orderItems = NSArray(contentsOfFile: "\(CACHES_PATH)/OrderList.plist")
            }
            
            
            // 提交了订单之后他会自动刷新
            if UserDefaults.standard.object(forKey: orderListRefreshRequireKey) != nil{
                refreshList()
            }
            
        }else{
            loginPleaseBtn.alpha = 1
        }
        tableView.delegate = self
        tableView.dataSource = self
        
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .stop, target: self, action: #selector(ListOrderViewController.close))
        
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        if isLogin() {
            if !logined{
                logined = true
                refreshList()
                loginPleaseBtn.alpha = 0
                refreshControl.alpha = 1
            }
        }else{
            logined = false
            loginPleaseBtn.alpha = 1
            refreshControl.alpha = 0
            orderItems = NSArray()
            tableView.reloadData()
        }
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        // 下拉刷新准备刷新
        if tableView.contentOffset.y < -108 {
            
            if refreshControl.state == .normal{
                refreshControl.readyToRefresh()
            }
            
        }else{
            // 松手刷新慢慢挪回去，取消刷新
            if refreshControl.state == .ready{
                refreshControl.endRefresh()
            }
            
        }
    }
    
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        // MARK: 下拉刷新出发
        if refreshControl.state == .ready{
            
            if logined {
                refreshControl.beginRefresh()
                refreshList()
            }
        }
    }
    
    func refreshList(){
        refreshControl.beginRefresh()
        spinnerBG.alpha = 1
        var resq = URLRequest(url: URL(string: "\(Fatcat.SERVER_DOMAIN_NAME)\(Fatcat.FILE_API)")!)
        resq.httpMethod = "POST"
        resq.httpBody = "act=getOrder".data(using: String.Encoding.utf8)
        
        URLSession.shared.dataTask(with: resq, completionHandler: { (reData:Data?, resp:URLResponse?, err:Error?) in
            DispatchQueue.main.async(execute: {
                self.spinnerBG.alpha = 0
                self.refreshControl.endRefresh()
                
            })
            if err == nil{
                if let data = reData {
                    print(String(data: data, encoding: .utf8) as Any)
                    
                    let jsonObj = try? JSONSerialization.jsonObject(with: data, options: .allowFragments)
                    if jsonObj != nil{
                        let jsonDic = jsonObj as? NSDictionary
                        if jsonDic != nil {
                            //print(jsonDic!)
                            let orderData = jsonDic?.object(forKey: "data") as? NSDictionary
                            if orderData != nil{
                                
                                self.orderItems = NSArray(array: orderData!.allValues)
                                
                                self.orderItems.write(toFile: "\(CACHES_PATH)/OrderList.plist", atomically: true)
                                UserDefaults.standard.removeObject(forKey: orderListRefreshRequireKey)
                                
                                DispatchQueue.main.async(execute: {
                                    self.tableView.reloadData()
                                    
                                })
                                
                                /*
                                let orderList = orderData?.objectForKey("order") as? NSDictionary
                                if orderList != nil{
                                    let tempOrderList = NSMutableDictionary(dictionary: orderList!)
                                    
                                    let orderListTemp = NSMutableArray()
                                    let orderItem = NSMutableArray()
                                    while tempOrderList.count != 0{
                                        for item in tempOrderList{
                                            if orderItem.count != 0{
                                                let orderID = (orderItem.objectAtIndex(0) as! NSDictionary).objectForKey("id") as! String
                                                let thisItemID = (item.value as! NSDictionary).objectForKey("id") as! String
                                                if orderID != thisItemID {
                                                    continue
                                                }
                                            }
                                            orderItem.addObject(item.value as! NSDictionary)
                                            tempOrderList.removeObjectForKey(item.key)
                                        }
                                        orderListTemp.addObject(NSArray(array: orderItem))
                                        orderItem.removeAllObjects()
                                    }
                                    orderListTemp.sortUsingFunction({ (obj1, obj2, nil) -> Int in
                                        let firstObj1 = (obj1 as! NSArray).firstObject as! NSDictionary
                                        let time1 = firstObj1.objectForKey("addtime") as! String
                                        let firstObj2 = (obj2 as! NSArray).firstObject as! NSDictionary
                                        let time2 = firstObj2.objectForKey("addtime") as! String
                                        if time1 < time2 {
                                            return 1
                                        }else if time1 > time2{
                                            return -1
                                        }
                                        return 0
                                        }, context: nil)
                                    self.orderItems = NSArray(array: orderListTemp)
                                    
                                NSUserDefaults.standardUserDefaults().removeObjectForKey("orderListRefreshRequire")
                                    
                                    //print(self.orderItems)
                                    self.orderItems.writeToFile("\(self.CACHES_PATH)/OrderList.plist", atomically: true)
                                    dispatch_async(dispatch_get_main_queue(), {
                                        self.tableView.reloadData()
                                        
                                    })
                                }
                                */
                                
                            }else{
                                self.orderItems = NSArray()
                                DispatchQueue.main.async(execute: {
                                    self.tableView.reloadData()
                                    
                                })
                            }
                            
                            
                        }
                    }else{
                        print("json error")
                    }
                    
                }
            }
            }) .resume()
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        if orderItems.count > 0{
            return orderItems.count
        }
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if orderItems.count > 0 {
            return (orderItems.object(at: section) as! NSArray).count + 2
        }
        return 0
        
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
//        if indexPath.row == 0{
//            return 44
//        }
//        if indexPath.row == orderItems.count + 1{
//            return 44
//        }
        let thisOrderItem = orderItems.object(at: indexPath.section) as! NSArray
        if indexPath.row > 0 && indexPath.row <= thisOrderItem.count {
            return 64
        }
        return 44
    }

    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: .default, reuseIdentifier: "item")
        if orderItems.count > 0{
            let thisOrderItem = orderItems.object(at: indexPath.section) as! NSArray
            let firstObj = thisOrderItem.firstObject as! NSDictionary
            switch indexPath.row {
            case 0:
                //            let timeLabel = UILabel(frame: CGRect(x: 16, y: 8, width: view.bounds.width - 32, height: 28))
                //            timeLabel.font = UIFont.systemFontOfSize(14)
                //            cell.addSubview(timeLabel)
                //
                //            timeLabel.text = "时间: \(firstObj.objectForKey("addtime") as! String)"
                
                let icon = UIImageView(frame: CGRect(x: 16, y: 10, width: 24, height: 24))
                icon.backgroundColor = UIColor.gray
                cell.addSubview(icon)
                
                let nameLabel = UILabel(frame: CGRect(x: 50, y: 8, width: view.bounds.width - 102, height: 28))
                nameLabel.font = UIFont.systemFont(ofSize: 14)
                cell.addSubview(nameLabel)
                
                
                let gotoMapBtn = UIButton()
                gotoMapBtn.frame = CGRect(x: view.bounds.width - 44, y: 2, width: 28, height: 28)
                gotoMapBtn.tag = indexPath.section
                gotoMapBtn.setImage(UIImage(named: "address"), for: UIControlState())
                cell.addSubview(gotoMapBtn)
                gotoMapBtn.addTarget(self, action: #selector(ListOrderViewController.gotoMap(_:)), for: .touchUpInside)
                
                let btnLabel = UILabel(frame: CGRect(x: view.bounds.width - 52, y: 32, width: 44, height: 8))
                btnLabel.font = UIFont.systemFont(ofSize: 10)
                btnLabel.textColor = UIColor.gray
                btnLabel.textAlignment = .center
                btnLabel.text = "显示地图"
                cell.addSubview(btnLabel)
                
                let shopName = firstObj.object(forKey: "nickname") as? String
                if shopName != nil {
                    nameLabel.text = shopName
                }
                
                let shopLogo = firstObj.object(forKey: "logo") as? String
                if shopLogo != nil{
                    let shopLogoURL = URL(string: shopLogo!)
                    if shopLogoURL != nil {
                        URLSession.shared.dataTask(with: shopLogoURL!, completionHandler: { (data:Data?, resp:URLResponse?, err:NSError?) in
                            if err == nil{
                                if data != nil{
                                    let image = UIImage(data: data!)
                                    icon.image = image
                                }
                            }
                        } as! (Data?, URLResponse?, Error?) -> Void)
                    }
                }
                
                let latitude = firstObj.object(forKey: "latitude") as? String
                let longitude = firstObj.object(forKey: "longitude") as? String
                if latitude == nil || longitude == nil {
                    gotoMapBtn.alpha = 0
                    btnLabel.alpha = 0
                }
                
                break
            case thisOrderItem.count+1:
                let downLabel = UILabel(frame: CGRect(x: 16, y: 8, width: view.bounds.width - 32, height: 28))
                downLabel.font = UIFont.systemFont(ofSize: 14)
                cell.addSubview(downLabel)
                
                var downText = ""
                
                
                var payStatus = firstObj.object(forKey: "pay_status") as? Int
                if payStatus == nil{
                    payStatus = Int(firstObj.object(forKey: "pay_status") as! String)
                }
                
                
                if payStatus == 0{
                    // MARK: 订单状态 未支付
                    downText = "未支付"
                    let payBtn = UIButton(frame: CGRect(x: view.bounds.width - 96, y: 8, width: 80, height: 28))
                    payBtn.tag = indexPath.section
                    payBtn.setTitle("支付", for: UIControlState())
                    payBtn.setTitleColor(Fatcat.SELECTED_COLOR, for: UIControlState())
                    payBtn.layer.borderColor = Fatcat.SELECTED_COLOR.cgColor
                    payBtn.layer.borderWidth = 1
                    payBtn.layer.cornerRadius = 4
                    cell.addSubview(payBtn)
                    payBtn.addTarget(self, action: #selector(ListOrderViewController.gotoPay(_:)), for: .touchUpInside)
                }else if payStatus == 1{
                    
                    
                    var postStatus = firstObj.object(forKey: "post_status") as? Int
                    if postStatus == nil{
                        postStatus = Int(firstObj.object(forKey: "post_status") as! String)
                    }
                    
                    var postMethod = firstObj.object(forKey: "post_method") as? Int
                    if postMethod == nil{
                        postMethod = Int(firstObj.object(forKey: "post_method") as! String)
                    }
                    
                    if postStatus == 0{
                        if postMethod == 1{
                            //MARK: 已支付 自取
                            downText = "已支付"
                            let getGoodsBtn = UIButton(frame: CGRect(x: view.bounds.width - 96, y: 8, width: 80, height: 28))
                            getGoodsBtn.tag = indexPath.section
                            getGoodsBtn.setTitle("取件", for: UIControlState())
                            getGoodsBtn.setTitleColor(Fatcat.SELECTED_COLOR, for: UIControlState())
                            getGoodsBtn.layer.borderColor = Fatcat.SELECTED_COLOR.cgColor
                            getGoodsBtn.layer.borderWidth = 1
                            getGoodsBtn.layer.cornerRadius = 4
                            cell.addSubview(getGoodsBtn)
                            getGoodsBtn.addTarget(self, action: #selector(ListOrderViewController.getGoodsScanCode(_:)), for: .touchUpInside)
                        }else{
                            //MARK: 已支付 派送中
                            downText = "派送中"
                        }
                    }else{
                        //MARK: 已支付 派送中
                        downText = "交易完成"
                    }
                    
                }else{
                    downText = "未知"
                }
                
                let totalPrice = firstObj.object(forKey: "total_price") as? String
                if totalPrice != nil{
                    downText +=  " ￥\(totalPrice!)"
                    let attrStr = NSMutableAttributedString(string: downText)
                    attrStr.addAttribute(NSFontAttributeName, value: UIFont.boldSystemFont(ofSize: 16), range: NSMakeRange(downText.characters.count - totalPrice!.characters.count, totalPrice!.characters.count))
                    attrStr.addAttribute(NSFontAttributeName, value: UIFont.boldSystemFont(ofSize: 14), range: NSMakeRange(downText.characters.count - totalPrice!.characters.count - 1, 1))
                    downLabel.attributedText = attrStr
                }else{
                    downLabel.text = downText
                }
                
                
                
                
                break
            default:
                let icon = UIImageView(frame: CGRect(x: 32, y: 8, width: 28, height: 28))
                icon.backgroundColor = UIColor.lightGray
                cell.addSubview(icon)
                
                let fileNameLabel = UILabel(frame: CGRect(x: 32+28+8, y: 8, width: view.bounds.width-84, height: 28))
                fileNameLabel.lineBreakMode = .byTruncatingMiddle
                fileNameLabel.font = UIFont.systemFont(ofSize: 14)
                cell.addSubview(fileNameLabel)
                
                let infoLabel = UILabel(frame: CGRect(x: 68, y: 36, width: view.bounds.width-84, height: 28))
                //            infoLabel.textAlignment = .Right
                infoLabel.font = UIFont.systemFont(ofSize: 14)
                infoLabel.textColor = UIColor.lightGray
                cell.addSubview(infoLabel)
                
                let thisFile = thisOrderItem.object(at: indexPath.row - 1) as! NSDictionary
                
                let fileName = thisFile.object(forKey: "sourceFileName") as? String
                fileNameLabel.text = fileName
                
                if fileName != nil {
                    let fileType = fileName!.components(separatedBy: ".").last
                    if fileType != nil {
                        if fileType == "doc" || fileType == "docx" {
                            icon.backgroundColor = UIColor.clear
                            icon.image = UIImage(named: "documents_icon_doc")
                        }else if fileType == "xls" || fileType == "xlsx" {
                            icon.backgroundColor = UIColor.clear
                            icon.image = UIImage(named: "documents_icon_xls")
                        }else if fileType == "ppt" || fileType == "pptx" {
                            icon.backgroundColor = UIColor.clear
                            icon.image = UIImage(named: "documents_icon_ppt")
                        }else if fileType == "pdf"{
                            icon.backgroundColor = UIColor.clear
                            icon.image = UIImage(named: "documents_icon_pdf")
                        }else if fileType == "txt"{
                            icon.backgroundColor = UIColor.clear
                            icon.image = UIImage(named: "documents_icon_txt")
                        }else if fileType == "png" || fileType == "jpg" || fileType == "jpeg" || fileType == "bmp" {
                            icon.backgroundColor = UIColor.clear
                            icon.image = UIImage(named: "photo")
                        }
                    }
                }
                
                var goodsNum = thisFile.object(forKey: "goods_number") as? Int
                if goodsNum == nil{
                    goodsNum = Int(thisFile.object(forKey: "goods_number") as! String)
                }
                var pageNum = thisFile.object(forKey: "pNum") as? Int
                if pageNum == nil{
                    pageNum = Int(thisFile.object(forKey: "pNum") as! String)
                }
                if goodsNum != nil && pageNum != nil{
                    infoLabel.text = "\(goodsNum!)份 x \(pageNum!)页"
                }
                
                break
            }
        }
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        /*
         // 闪烁动画
        for i in 0..<(orderItems.objectAtIndex(indexPath.section) as! NSArray).count+2{
            if i != indexPath.row{
                tableView.selectRowAtIndexPath(NSIndexPath(forRow: i, inSection: indexPath.section), animated: true, scrollPosition: .None)
            }
            
        }
        for i in 0..<(orderItems.objectAtIndex(indexPath.section) as! NSArray).count+2{
            
            tableView.deselectRowAtIndexPath(NSIndexPath(forRow: i, inSection: indexPath.section), animated: true)
        }
        */
        
        tableView.deselectRow(at: indexPath, animated: true)
        let files = orderItems.object(at: indexPath.section) as! NSArray
        if indexPath.row > 0 && indexPath.row <= files.count{
            let thisFile = files.object(at: indexPath.row - 1) as! NSDictionary
            let filePath = thisFile.object(forKey: "filePath") as? String
            let fileName = thisFile.object(forKey: "sourceFileName") as? String
            if filePath != nil && fileName != nil{
                present(HTMLStringViewController(path: filePath!, name: fileName!), animated: true, completion: nil)
            }
            
        }
        
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        if section == orderItems.count - 1{
            return 64
        }
        return 0
    }
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let footView = UIView(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: 64))
        
        if orderItems.count > 0{
            if section == orderItems.count - 1{
                
            }
        }else{
            let emptyLabel = UILabel(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: 64))
            emptyLabel.text = "暂无数据"
            emptyLabel.textColor = UIColor.lightGray
            emptyLabel.textAlignment = .center
            footView.addSubview(emptyLabel)
        }
        
        return footView
    }
    
    func getGoodsScanCode(_ sender: UIButton){
        let orderItem = (orderItems.object(at: sender.tag) as! NSArray).firstObject as! NSDictionary
        var orderID = orderItem.object(forKey: "id") as? Int
        if orderID == nil{
            orderID = Int(orderItem.object(forKey: "id") as! String)
        }
        print("ready to get goods by order id: \(orderID ?? 0)")
        hidesBottomBarWhenPushed = true
        let getScanVC = GetScanViewController()
        getScanVC.delegate = self
        getScanVC.oid = "\(orderID!)"
        navigationController?.pushViewController(getScanVC, animated: true)
    }
    
    func didFinishedGetCode(_ code: String?, orderID: String?) {
        spinnerBG.alpha = 1
        if code != nil && orderID != nil{
            var resq = URLRequest(url: URL(string: "\(Fatcat.SERVER_DOMAIN_NAME)\(Fatcat.FILE_API)")!)
            resq.httpMethod = "POST"
            resq.httpBody = "act=userTakeGoods&order_id=\(orderID!)&\(code!)".data(using: String.Encoding.utf8)
            
            URLSession.shared.dataTask(with: resq, completionHandler: { (reData:Data?, resp:URLResponse?, err:Error?) in
//                dispatch_async(dispatch_get_main_queue(), { 
//                    self.spinnerBG.alpha = 0
//                })
                var failed = true
                if err == nil{
                    if let data = reData{
                        
                        print(String(data: data, encoding: String.Encoding.utf8) as Any)
                        let jsonObj = try? JSONSerialization.jsonObject(with: data, options: .allowFragments)
                        if jsonObj != nil{
                            let jsonDic = jsonObj as? NSDictionary
                            if jsonDic != nil {
                                let reCode = jsonDic?.object(forKey: "code") as! Int
                                if reCode == 200 {
                                    failed = false
                                    DispatchQueue.main.async(execute: { 
                                        self.refreshList()
                                    })
                                }
                            }
                        }
                    }
                }
                if failed{
                    DispatchQueue.main.async(execute: {
                        let alert = UIAlertController(title: "请求失败", message: nil, preferredStyle: .alert)
                        alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
                        self.present(alert, animated: true, completion: nil)
                    })
                }
            }).resume()
        }else{
            print("nil error")
        }
        
        
    }
    
    func gotoMap(_ sender:UIButton){
        let orderItem = (orderItems.object(at: sender.tag) as! NSArray).firstObject as! NSDictionary
        let shopname = orderItem.object(forKey: "nickname") as? String
        let latitude = orderItem.object(forKey: "latitude") as? String
        let longitude = orderItem.object(forKey: "longitude") as? String
        if latitude != nil && longitude != nil {
            let latitudeValue = Double(latitude!)
            let longitudeValue = Double(longitude!)
            if latitudeValue != nil && longitudeValue != nil {
                let location = CLLocationCoordinate2D(latitude: latitudeValue!, longitude: longitudeValue!)
                let map = MKMapItem(placemark: MKPlacemark(coordinate: location, addressDictionary: nil))
                map.name = shopname
                MKMapItem.openMaps(with: [map], launchOptions: [MKLaunchOptionsMapCenterKey: true])
            }
            
        }
        
        
    }
    
    func gotoPay(_ sender:UIButton){
        let orderItem = (orderItems.object(at: sender.tag) as! NSArray).firstObject as! NSDictionary
        
        var orderID = orderItem.object(forKey: "id") as? Int
        if orderID == nil{
            orderID = Int(orderItem.object(forKey: "id") as! String)
        }
        print("ready to pay by order id: \(orderID ?? 0)")
        //MARK: handle payment
        var totalPrice = orderItem.object(forKey: "total_price") as? Double
        if totalPrice == nil{
            totalPrice = Double(orderItem.object(forKey: "total_price") as! String)
        }
        let payVC = PayViewController(amount: totalPrice!)
        payVC.delegate = self
        present(payVC, animated: true, completion: nil)
    }
    
    func didFinishedPay(_ result: Bool) {
        if result{
            refreshList()
        }
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        hidesBottomBarWhenPushed = false
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    func gotoLogin(){
        print("login")
        //present(UDLoginViewController(), animated: true, completion: nil)
    }
    func close(){
        dismiss(animated: true, completion: nil)
    }

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
